const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
const BadRequest = require('http-errors').BadRequest;
const NotFoundError = require('../../utils/errors').NotFoundError;
const success = require('../../utils/responses').success;
const failure = require('../../utils/responses').failure;
const moment = require('moment');
moment.locale('zh-cn');

mongoose.connect('mongodb://localhost:27017/control-book', {
    useNewUrlParser: true,
    useUnifiedTopology: true
});

const User = require('../../models/user');
const { updateLocale } = require('moment');

// 获取所有用户
router.get('/', async function (req, res) {
  try {
      const query = req.query;

      // 获取分页所需要的两个参数，currentPage和pageSize
      // 如果没有传递这两个参数，就使用默认值
      // 默认是1页，默认每页显示10条数据
      const currentPage = Math.abs(Number(query.currentPage) || 1);
      const pageSize = Math.abs(Number(query.pageSize) || 10);

      const skip = (currentPage - 1) * pageSize;

      const condition = {};

      if (query.name) {
          condition.name = { $regex: new RegExp(query.name, 'i') };
      }
      if (query.borrowUser === 'true') {
          condition.borrowUser = true;
      } else if (query.borrowUser === 'false') {
          condition.borrowUser = false;
      }

      const totalCount = await User.countDocuments(condition);
      const users = await User.find(condition)
        .skip(skip)
        .limit(pageSize)
        .sort({ _id: -1 });

      success(res, '用户查询成功', {
          users,
          pagination: {
              total: totalCount,
              currentPage,
              pageSize
          }
      });
  } catch (error) {
      failure(res, error);
  }
});

// 获取单个用户详细信息
router.get('/:_id', async function (req, res) {
  try {
      const user = await User.findById(req.params._id);
      if (!user) {
          throw new NotFoundError(`ID: ${req.params._id}的用户未找到`);
      }
      success(res, '用户查询成功', { user });
  } catch (error) {
      failure(res, error);
  }
});

// 创建用户
router.post('/', async function (req, res) {
  try {
      const body = req.body;
      const user = new User(body);
      await user.save();
      success(res, '用户创建成功', { user }, 201);
  } catch (error) {
    console.log(error);
      failure(res, error);
  }
});

// 删除用户
router.delete('/:id', async function (req, res) {
  try {
      const user = await User.findById(req.params.id);
      if (!user) {
          throw new NotFoundError(`ID: ${req.params.id}的用户未找到`);
      }
      await user.remove();
      success(res, '用户删除成功');
  } catch (error) {
      failure(res, error);
  }
});

// 更新用户
router.put('/:_id', async function (req, res) {
  try {
      const user = await User.findById(req.params._id);
      if (!user) {
          throw new NotFoundError(`ID: ${req.params._id}的用户未找到`);
      }
      const body = filterUser(req);

      const isUsernameUpdated = Object.keys(body).includes('username');
      if (isUsernameUpdated && body.username !== user.username) {
          throw new BadRequest('用户名不可修改');
      }
      const updatedUser = await User.findByIdAndUpdate(req.params._id, body, { new: true });

    //   Object.assign(user, body);
    //   await user.save();
      success(res, '用户更新成功', { updatedUser });
  } catch (error) {
    console.log(error);
      failure(res, error);
  }
});

function filterUser(req) {
  return {
      role: req.body.role,
      updatedAt: moment().format('YYYY-MM-DD HH:mm:ss'),
  };
}

module.exports = router;